package com.neusoft.hifly.netty.socket;

import java.time.LocalDateTime;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class SocketClient {

	//主机名/IP
	private String host;
	//端口号
	private int port;

	public SocketClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	//启动方法
	public void start() throws Exception {
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(workerGroup);
			bootstrap.channel(NioSocketChannel.class);
			bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
			bootstrap.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel channel) throws Exception {
					channel.pipeline().addLast("decoder", new StringDecoder());
					channel.pipeline().addLast("encoder", new StringEncoder());
					channel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
						@Override
						protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
							System.out.println("收到响应：" + msg);
						}
					});
				}
			});

			//建立连接
			ChannelFuture future = bootstrap.connect(host, port).sync();

			while (true) {
				System.out.println(String.format("向服务器发送消息... %s", LocalDateTime.now() + ": hello socket!"));
				//发送消息
				future.channel().writeAndFlush(LocalDateTime.now() + ": hello socket!");
				Thread.sleep(1 * 1000);
			}

			//等待服务监听端口关闭
			//			future.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
		}
	}

	//测试代码
	public static void main(String[] args) {
		try {
			String host = "192.168.101.40";
			int port = 9003;
			//			String host = "192.168.66.45";
			//			int port = 49527;
			//			String host = "127.0.0.1";
			//			int port = 49527;
			new SocketClient(host, port).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
